mod config;
use raft4rs::entity::{Decode, Entry};
use std::fs;
use std::io::prelude::*;

fn main() {
    let file_path =
        // "/Users/sunjian11/rustworkspace/projects/rust-raft/example/data/raft1/1/raft_1.log";
    // "/Users/sunjian11/rustworkspace/projects/rust-raft/example/data/raft2/1/raft_1.log";
    "/Users/sunjian11/rustworkspace/projects/rust-raft/example/data/raft3/1/raft_3.log";
    let mut file = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .read(true)
        .open(file_path)
        .unwrap();

    let mut pre = 0;

    loop {
        let dl = read_u32(&mut file) as u64;
        if dl == 0 {
            break;
        }
        let mut buf = vec![0; dl as usize];
        file.read_exact(&mut buf).unwrap();
        let entry = Entry::decode(&buf).unwrap();

        if pre > 0 {
            if entry.info().1 - pre != 1 {
                panic!(format!(
                    "id is not sequential now:{}  pre:{}",
                    entry.info().1,
                    pre
                ));
            }
        }
        pre = entry.info().1;
        println!("{:?}", entry.info());
    }
}

fn read_u32(file: &mut fs::File) -> u32 {
    let mut output = [0u8; 4];
    file.read_exact(&mut output[..]);
    u32::from_be_bytes(output)
}
